/*
 * Created by Wildish on 2016-10-31
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hybridframework.utils.audio;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import java.io.File;

public class SoundPoolHelper extends SoundBase {
    private SoundPool pool;
    private int streamVolume;

    public SoundPoolHelper(Context context) {
        super(context);
        pool = new SoundPool(DEFAULT_SOUNDPOOL_SIZE, AudioManager.STREAM_MUSIC, 0);
        AudioManager mgr = (AudioManager)this.context.getSystemService(Context.AUDIO_SERVICE);
        streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    /**
     * 加载声音
     */
    public boolean loadSoundById(String key, SoundItem item) {
        if(!sMap.containsKey(key)) {
            int streamId = pool.load(context, item.getRawId(), item.getPriority());
            item.setStreamId(streamId);
            sMap.put(key, item);
        }

        return true;
    }

    /**
     *
     * @param key
     * @param item
     */
    public boolean loadSoundByPath(String key, SoundItem item) {
        File file = new File(item.getSoundPath());
        if(file.exists()) {
            int streamId = pool.load(file.getAbsolutePath(), item.getPriority());
            item.setStreamId(streamId);
            item.setKey(key);
            sMap.put(key, item);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 播放声音
     * @param key
     */
    public void playSound(String key, String status) {
        SoundItem item = sMap.get(key);

        switch (status) {
            case "play":
                if(currentSound != null && !currentSound.getKey().equals(key)) {
                    pool.stop(currentSound.getStreamId());
                }
                int streamId = pool.play(item.getStreamId(), streamVolume, streamVolume, item.getPriority(), item.getLoop(), item.getRate());
                item.setStreamId(streamId);
                currentSound = item;
                break;
            case "pause":
                if(currentSound != null && currentSound.getKey().equals(key)) {
                    pool.pause(currentSound.getStreamId());
                }
                break;
        }
    }

    @Override
    public void releaseAll() {
        if(currentSound != null) {
            pool.stop(currentSound.getStreamId());
        }
        if(pool != null) {
            pool.release();
        }
        currentSound = null;
        sMap.clear();
    }
}
